﻿using System;
using System.IO;
using System.Threading;
using Sasa.QualityTools.CodeAnalysis.Common;

namespace Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.Models
{
    internal class RuleSetConverter
    {
        private string customDir;


        internal RuleSetConverter(string customDir)
        {
            this.customDir = customDir;
        }


        internal string Convert(string value)
        {
            if (String.IsNullOrWhiteSpace(value))
            {
                return null;
            }

            var fileName = Path.GetFileName(value);
            var culture = Thread.CurrentThread.CurrentUICulture;

            var bundleDir = Path.Combine(Environment.GetEnvironmentVariable("VS100COMNTOOLS"), "..", "..", "Team Tools", "Static Analysis Tools", "Rule Sets");
            if (value.StartsWith(bundleDir, false, culture))
            {
                return "Bundled;" + fileName;
            }
            else if (value.StartsWith(customDir, false, culture))
            {
                return "Custom;" + fileName;
            }
            else
            {
                throw new InvalidOperationException("The specified ruleset path (" + value + ") is invalid.");
            }
        }

        internal string Reverse(string value)
        {
            if (String.IsNullOrWhiteSpace(value) || !value.Contains(";"))
            {
                return null;
            }

            var tokens = value.Split(new string[] { ";" }, 2, StringSplitOptions.RemoveEmptyEntries);
            switch (tokens[0])
            {
                case "Bundled":
                    return Path.Combine(Environment.GetEnvironmentVariable("VS100COMNTOOLS"), "..", "..", "Team Tools", "Static Analysis Tools", "Rule Sets", tokens[1]);
                case "Custom":
                    return Path.Combine(customDir, tokens[1]);
                default:
                    throw new InvalidOperationException("The specified ruleset format (" + value + ") is invalid.");
            }
        }
    }
}